package com.test.demo1.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class VMWareManager {

    public static void stopVM(String vmxPath) {
        try {
            // 检查虚拟机是否运行
            Process listProcess = Runtime.getRuntime().exec("vmrun list");
            BufferedReader reader = new BufferedReader(new InputStreamReader(listProcess.getInputStream()));
            String line;
            boolean isRunning = false;
            while ((line = reader.readLine()) != null) {
                if (line.contains(vmxPath)) {
                    isRunning = true;
                    break;
                }
            }
            listProcess.waitFor();

            if (isRunning) {
                // 关闭虚拟机
                Process stopProcess = Runtime.getRuntime().exec(new String[]{"vmrun", "stop", vmxPath, "hard"});
                stopProcess.waitFor();
                System.out.println("虚拟机已关闭");
            } else {
                System.out.println("虚拟机未运行");
            }

            // 删除锁文件
            deleteLockFiles(vmxPath);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void deleteLockFiles(String vmxPath) {
        File vmxFile = new File(vmxPath);
        File parentDir = vmxFile.getParentFile();
        File[] lockFiles = parentDir.listFiles((dir, name) -> name.endsWith(".lck") || name.endsWith(".lock"));
        if (lockFiles != null) {
            for (File lockFile : lockFiles) {
                if (lockFile.delete()) {
                    System.out.println("删除锁文件: " + lockFile.getName());
                } else {
                    System.out.println("无法删除锁文件: " + lockFile.getName());
                }
            }
        }
    }

    public static void main(String[] args) {
        stopVM("D:\\学习机3\\学习机3.vmx");
    }
}
